package biz.yfsoft.app.fastframework.admin;

import java.util.Map;

import biz.yfsoft.app.fastframework.bo.Bo;
import biz.yfsoft.app.fastframework.core.Fast;
import biz.yfsoft.app.fastframework.core.hex.PasswordErrorException;

import com.jfinal.aop.Before;
import com.jfinal.kit.EncryptionKit;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;


public class UserController extends AdminController {
	
	@Override
	protected String getTable() {
		return "sys_user u left join sys_user_role ur on u.id = ur.userid left join sys_role r on ur.roleid = r.id ";
	}
	protected String getCondition(){
		return "u.status > 0";
	}
	
	public void index() {
		render("/admin/users/list.jsp");
	}
	
	@Override
	protected String getSearchFields(String searchs) {
		if(isSqlInject(searchs)){
			return " 1 = 2 ";
		}
		if(searchs == null){
			return " 1 = 1 ";
		}
		return " login_name like '%{key}%' or email like '%{key}%' or display_name like '%{key}%' ".replace("{key}", searchs);
	}

	@Override
	protected Map<String, Object> prevAdd(Map<String, Object> args) {
		String encode = getPara("pass_encode", "MD5");
		String pass = getPara("login_pass", "123");
		pass = EncryptionKit.encrypt(encode, pass);
		args.put("login_pass", pass);
		return args;
	}
	
	@Override
	protected String getField(){
		return "u.id id, u.login_name login_name,u.display_name display_name,u.email email,u.is_admin is_admin,ur.roleid, u.status status, u.createtime createtime, r.title role ";
	}

	@Before({Tx.class})
	public void save(){
		Record record = new Record();
		boolean is = false;
		try{
			String id = getPara("id");
			Map<String,Object> args = getParams();
			//需要对密码进行加密
			args = prevAdd(args);
			int roleid = Integer.parseInt(args.remove("roleid").toString());
			if(id == null){
				Bo user = new Bo();
				user.setColumns(args);
				user.create();
				is = Db.save("sys_user", user);
				
				id = user.getLong("id").toString();
			}else{
				record = Db.findById("sys_user", id);
				record.setColumns(args);
				Bo user = new Bo();
				user.setColumns(record);
				is = Db.update("sys_user", record);
			}
			
			if(is && roleid != 0){
				record = Db.findFirst("SELECT * FROM sys_user_role WHERE userid=?" , id);
				if(record != null)
					is = (Db.update("UPDATE sys_user_role SET roleid=? WHERE userid=?", roleid, id) > 0);
				else{
					record = new Record();
					record.set("roleid", roleid);
					record.set("userid", id);
					is = Db.save("sys_user_role", record);
				}
			}	
		}catch(ActiveRecordException hex){
			renderJson(wrapJson(-2,"操作失败!可能原因如下：\n"+hex.getMessage()));
			return;
		}
		if(is)
			renderJson(wrapJson(0,"",record));
		else
			renderJson(wrapJson(-1,"修改失败!"));
	}
	
	/**
	 * 删除实体的信息
	 * 通过url传递名称为id[]的参数
	 * 以英文逗号隔开
	 * 通过更新 status＝ －1 来进行删除状态的标记
	 */
	@Before({Tx.class})
	@Override
	public void del(){
		String ids = getPara("id[]");
		//删除对应的角色关联信息
		
		int rows = Db.update("delete from sys_user_role where userid in ("+ids+")");
		rows = Db.update("update sys_user set login_name = concat(login_name,'_delete'),email = concat(email,'_delete'),status= -1 , updatetime = ? where id in ("+ ids+")",System.currentTimeMillis());
		if(rows>0){
			renderJson(wrapJson(0,"",rows));
			invokeResult = true;
		}else{
			renderJson(wrapJson(-1,"删除失败!"));
			invokeResult = false;
		}
	}
	
	
	public void changePassword(){
		if("GET".equalsIgnoreCase(this.getRequest().getMethod())){
			render("/admin/users/changePassword.jsp");
		}else{
			String newPass = getPara("newpassword");
			String oldPass = getPara("oldpassword");
			try{
				Fast.me().changePwd(oldPass, newPass);
				
				renderJson(wrapJson(0,"修改成功!"));
			}catch(PasswordErrorException hex){
				renderJson(wrapJson(-2,"原始密码输入错误!"));
			}
		}
	}
}
